package com.loiot.baqi.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.loiot.baqi.controller.response.AjaxResponse;
import com.loiot.baqi.controller.response.Pager;
import com.loiot.baqi.dao.WeiAccountQqGroupDao;
import com.loiot.baqi.pojo.TgQqMember;
import com.loiot.baqi.pojo.WeiAccountQqGroup;
import com.loiot.baqi.status.ImportStatus;
import com.loiot.baqi.status.SubscribeStatus;
import com.loiot.commons.utils.IOUtil;


/**
 * 建议 逻辑类。
 * 
 * @author  wangzx 
 * @creation 2016-03-21
 */
@Service("weiAccountQqGroupService")
@Transactional
public class WeiAccountQqGroupService{
    
    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    @Resource
	private WeiAccountQqGroupDao weiAccountQqGroupDao;
    
    @Resource
   	private TgQqMemberService tgQqMemberService;
	
	
	 /**
     * 查询 建议列表分页
     * 
     * @param name 建议名称
     * @param pageIndex 页索引
     * @return
     */
    public Pager<WeiAccountQqGroup> queryWeiAccountQqGroupOverviewListPage(HashMap<String,Object> pMap, int pageIndex)throws Exception {

        // 查询建议列表总条数
        int totalResults = weiAccountQqGroupDao.getWeiAccountQqGroupListCount(pMap);

        // 构造一个分页器
        Pager<WeiAccountQqGroup> pager = new Pager<WeiAccountQqGroup>(totalResults, pageIndex);

        // 查询建议列表
        List<WeiAccountQqGroup> weiAccountQqGroupList = weiAccountQqGroupDao.queryWeiAccountQqGroupOverviewList(pMap, pager.getSkipResults(),
                pager.getMaxResults());
        pager.setData(weiAccountQqGroupList);
        return pager;
    }
    
    /**
     * 查询 建议列表分页
     * 
     * @param name 建议名称
     * @param pageIndex 页索引
     * @return
     */
    public Pager<WeiAccountQqGroup> queryWeiAccountQqGroupListPage(HashMap<String,Object> pMap, int pageIndex)throws Exception {

        // 查询建议列表总条数
        int totalResults = weiAccountQqGroupDao.getWeiAccountQqGroupListCount(pMap);

        // 构造一个分页器
        Pager<WeiAccountQqGroup> pager = new Pager<WeiAccountQqGroup>(totalResults, pageIndex);

        // 查询建议列表
        List<WeiAccountQqGroup> weiAccountQqGroupList = weiAccountQqGroupDao.queryWeiAccountQqGroupList(pMap, pager.getSkipResults(),
                pager.getMaxResults());
        pager.setData(weiAccountQqGroupList);
        return pager;
    }
    
    
    
    
    /**
     * 查询 建议（假）分页
     * 
     * @param name 建议名称
     * @param pageIndex 页索引
     * @return
     */
    public Pager<WeiAccountQqGroup> queryFlasePageList(HashMap<String,Object> pMap, int pageIndex)throws Exception {
    	//假分页
    	Pager<WeiAccountQqGroup> pager = this.setPkList(pMap,pageIndex);
    	List<WeiAccountQqGroup> weiAccountQqGroupList = weiAccountQqGroupDao.queryWeiAccountQqGroupList(pMap);
        pager.setData(weiAccountQqGroupList);
        return pager;
    }
    
    /**
     * 设置 假分页id集合到Map中
     * @param pMap
     * @param pageIndex
     * @return
     * @throws Exception
     */
    public Pager<WeiAccountQqGroup> setPkList(HashMap<String,Object> pMap,int pageIndex) throws Exception{
    	  // 查询职位匹配信息列表总条数
        List<WeiAccountQqGroup> list = weiAccountQqGroupDao.queryWeiAccountQqGroupList(pMap);
        // 构造一个分页器
        Pager<WeiAccountQqGroup> pager = new Pager<WeiAccountQqGroup>(list.size(), pageIndex, 5,list);
        List<WeiAccountQqGroup> idsList = pager.getCurrentPageData();
        List<Long> ids =this.getIds(idsList);
        pMap.put("ids", ids);
        return pager;
    }
	
	 /**
     * 添加 建议
     * 
     * @param p 参数对象
     */
    public WeiAccountQqGroup addWeiAccountQqGroup(WeiAccountQqGroup p)throws Exception {
       return  weiAccountQqGroupDao.addWeiAccountQqGroup(p);
    }
    
    /**
     * 修改 建议
     * 
     * @param p 参数对象
     */
    public void updateWeiAccountQqGroup(WeiAccountQqGroup p)throws Exception {
        weiAccountQqGroupDao.updateWeiAccountQqGroup(p);
    }
    
    /**
     * 修改 建议
     * 
     * @param p 参数对象
     */
    public void updateWeiAccountQqGroup(HashMap<String,Object> pMap)throws Exception {
        weiAccountQqGroupDao.updateWeiAccountQqGroup(pMap);
    }
    
    /**
     * 删除  建议
     * 
     * @param id 主键
     */
    public void deleteWeiAccountQqGroup(java.lang.Long id)throws Exception {
        weiAccountQqGroupDao.deleteWeiAccountQqGroup(id);
    }
    
    /**
     * 删除  建议
     * 
     * @param id 主键
     */
    public void deleteWeiAccountQqGroup(WeiAccountQqGroup p)throws Exception {
        weiAccountQqGroupDao.deleteWeiAccountQqGroup(p);
    }
    
    /**
     * 获得  建议
     * 
     * @param id 建议Id
     * 
     * @return 返回与ID匹配的建议
     */
    public WeiAccountQqGroup getWeiAccountQqGroupById(java.lang.Long id)throws Exception {
        return  weiAccountQqGroupDao.getWeiAccountQqGroupById(id);
    }
    
    /**
     * 获得  建议
     * 
     * @param id 建议Id
     * 
     * @return 返回与ID匹配的建议
     */
    public WeiAccountQqGroup getWeiAccountQqGroupById(java.lang.Long id,Long accountId)throws Exception {
        return  weiAccountQqGroupDao.getWeiAccountQqGroupById(id,accountId);
    }
    
    
    /**
     * 获得  建议
     * 
     * @param id 建议Id
     * 
     */
    public WeiAccountQqGroup getWeiAccountQqGroup(HashMap<String,Object> pMap)throws Exception {
    	return (WeiAccountQqGroup) weiAccountQqGroupDao.getWeiAccountQqGroup(pMap);
    }
    /**
     * 获得  建议
     * 
     * @param name 建议名称
     * 
     * @return 返回与NAME匹配的建议
     */
    public WeiAccountQqGroup getWeiAccountQqGroupByName(String name)throws Exception {
        return  weiAccountQqGroupDao.getWeiAccountQqGroupByName(name);
    }
    
    /**
     * 查询 建议列表
     * @return 建议列表
     */
    public List<WeiAccountQqGroup> queryWeiAccountQqGroupList(HashMap<String,Object> pMap)throws Exception {
        return  weiAccountQqGroupDao.queryWeiAccountQqGroupList(pMap);
    }
    
    /**
     * 查询 建议列表
     * @return 建议列表
     */
    public List<WeiAccountQqGroup> queryWeiAccountQqGroupList(WeiAccountQqGroup p)throws Exception {
        return  weiAccountQqGroupDao.queryWeiAccountQqGroupList(p);
    }
    
    /**
     * 查询  建议列表条数
     * 
     * @param name 建议名称
     * @return 建议列表条数
     */
    
    public int getWeiAccountQqGroupOverviewListCount(HashMap<String,Object> pMap)throws Exception {
        return  weiAccountQqGroupDao.getWeiAccountQqGroupOverviewListCount(pMap);
    }
    
    /**
     * 查询  建议列表条数
     * 
     * @param name 建议名称
     * @return 建议列表条数
     */
    
    public int getWeiAccountQqGroupListCount(HashMap<String,Object> pMap)throws Exception {
        return  weiAccountQqGroupDao.getWeiAccountQqGroupListCount(pMap);
    }
    
    /**
     * 查询id集合
     * @return
     */
    public List<Long> getIds(List<WeiAccountQqGroup> list) {
    	List<Long> idsList = null;
        if(list!=null && list.size()>0) {
        	idsList = new ArrayList<Long>();
        	for (WeiAccountQqGroup b : list) {
            	idsList.add(null);
            }
        }
        return idsList;
    }
    
    /**
     * 统计 建议列表
     * 
     * @return 建议列表
     */
    public List<HashMap<String,Object>> statisticsWeiAccountQqGroupInfo(HashMap<String, Object> pMap )throws Exception {
    	return  weiAccountQqGroupDao.statisticsWeiAccountQqGroupInfo(pMap);
    }

    /**
     * 批量导入群成员.
     * @param id 群id
     * @param inPerson 录入人id
     * @param is 文件输入流
     * @throws Exception
     */
	public AjaxResponse importMembers(Long id, Long inPerson, InputStream is)
			throws Exception {
		// 解析群成员
		WeiAccountQqGroup group = weiAccountQqGroupDao
				.getWeiAccountQqGroupById(id);
		//List<List<String>> list = Parser.parseFile(is);
		List<String[]> list = Parser.readeQQ(is);
		List<TgQqMember> members = convert2(group.getGroupId(), inPerson, list);
		
		//List<TgQqMember> members =null;
		 int totalCount = members.size();
		//int totalCount=0;
		if (totalCount == 0) {
			return new AjaxResponse(1, "文件中没有群成员记录！本次导入0条！");
		}

		// 剔除已存在QQ
		excludeExistMembers(members);
		if (members.size() == 0) {
			return new AjaxResponse(1, "群成员均已存在！本次导入0条！");
		}

		// 导入群成员
		tgQqMemberService.addTgQqMember(members);

		// 更新导入状态
		group.setImportStatus(ImportStatus.IMPORTED.getCode());
		group.setImportTime(new Date());
		weiAccountQqGroupDao.updateWeiAccountQqGroup(group);
		return new AjaxResponse(1, "文件中共有记录" + totalCount + "条，已存在"
				+ (totalCount - members.size()) + "条，本次导入" + members.size()
				+ "条！");
	}

	/**
	 * 剔除已存在QQ号.
	 * @param members
	 * @throws Exception
	 */
	private void excludeExistMembers(List<TgQqMember> members) throws Exception {
		String[] numbers = new String[members.size()];
		for (int i = 0; i < members.size(); i++) {
			numbers[i] = members.get(i).getNumber();
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("qqGroup", members.get(0).getQqGroup());
		paramMap.put("numbers", numbers);
		List<TgQqMember> existMembers = tgQqMemberService
				.getExistMemberList(paramMap);
		if (CollectionUtils.isNotEmpty(existMembers)) {
			Map<String, String> existNumbers = new HashMap<String, String>();
			for (TgQqMember member : existMembers) {
				existNumbers.put(member.getNumber(), "");
			}
			for (int i = members.size() - 1; i >= 0; i--) {
				if (existNumbers.get(members.get(i).getNumber()) != null) {
					members.remove(i);
				}
			}
		}
	}

	/**
	 * 将解析结果转为TgQqMember对象.
	 * @param groupId 群id
	 * @param inPerson 录入人id
	 * @param list 解析结果
	 * @return TgQqMember对象列表
	 */
	private List<TgQqMember> convert(Long groupId, Long inPerson, List<List<String>> list) {
		List<TgQqMember> members = new ArrayList<TgQqMember>();
		TgQqMember member = null;
		for(List<String> item : list){
			if(item == null){
				continue;
			}
			member = new TgQqMember();
			member.setQqGroup(groupId);
			member.setName(item.get(1));
			member.setNumber(item.get(3));
			member.setSubscribeStatus(SubscribeStatus.NOT_SUBSCRIB.getCode());
			member.setInPerson(inPerson);
			member.setInTime(new Date());
			members.add(member);
		}
		return members;
	}
	
	/**
	 * 将解析结果转为TgQqMember对象.
	 * @param groupId 群id
	 * @param inPerson 录入人id
	 * @param list 解析结果
	 * @return TgQqMember对象列表
	 */
	private List<TgQqMember> convert2(Long groupId, Long inPerson, List<String[]> list) {
		List<TgQqMember> members = new ArrayList<TgQqMember>();
		TgQqMember member = null;
		for(String item[] : list){
			if(item == null){
				continue;
			}
			member = new TgQqMember();
			member.setQqGroup(groupId);
			member.setName(item[0]);
			member.setNumber(item[1]);
			member.setSubscribeStatus(SubscribeStatus.NOT_SUBSCRIB.getCode());
			member.setInPerson(inPerson);
			member.setInTime(new Date());
			members.add(member);
		}
		return members;
	}
	
	/**
	 * @author genein
	 *
	 */
	static class Parser{
		/**
		 * 最后一列列名
		 */
		public static final String LAST_COL_NAME = "最后发言";
		/**
		 * 系统换行分隔符
		 */
		public static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");
		/**
		 * 制表符
		 */
		public static final String TAB = "\t";
		
		/**
		 * 将文件解析为对象.
		 * @param is
		 * @return
		 * @throws IOException
		 */
		public static List<List<String>> parseFile(InputStream is) throws IOException {
			
			String sfff=IOUtil.toString(is);
			// 列数
			boolean isReadCols = true;
			int colCount = 0;
			
			List<List<String>> list = new ArrayList<List<String>>();
			String s = null;
			StringBuffer sb = new StringBuffer();
			List<String> member = null;
			InputStreamReader isr = null;
			BufferedReader read = null;
			try {
				isr = new InputStreamReader(is, "utf-8");
				read = new BufferedReader(isr);
				while ((s = read.readLine()) != null) {
					s = s.trim();
					if (s.startsWith(TAB)) {
						s = s.replaceFirst(TAB, "");
					}
					if (s.endsWith(TAB)) {
						s = s.substring(0, s.length() - 1);
					}
					// 先解析列信息
					if(isReadCols){
						if(StringUtils.isBlank(s)){
							continue;
						}
						if (!"".equals(sb.toString())) {
							sb.append(TAB);
						}
						sb.append(s);
						if(sb.toString().endsWith(LAST_COL_NAME)){
							isReadCols = false;
							colCount = sb.toString().split(TAB).length;
							sb = new StringBuffer();
						}
						continue;
					}
					
					// 解析成员信息
					String[] info = s.split(TAB);
					if (info.length >= colCount) {
						member = justify(info, colCount);
						list.add(member);
					} else {
						if (!"".equals(sb.toString())) {
							sb.append(TAB);
						}
						sb.append(s.replaceAll("[" + TAB + "|" + LINE_SEPARATOR
								+ "]+", TAB));
						info = sb.toString().split(TAB);
						if (info.length >= colCount) {
							member = justify(info, colCount);
							list.add(member);
							sb = new StringBuffer();
						}
					}
				}
			} finally {
				if (read != null) {
					try {
						read.close();
					} catch (Exception e) {
					}
				}
				if (isr != null) {
					try {
						isr.close();
					} catch (Exception e) {
					}
				}
			}
			return list;
		}
		
		/**
		 * @Desc : google 解析群空间
		 * @Author: RICK
		 * @Date : 2017年3月17日上午12:19:45
		 * @params:@param filePath
		 *
		 */
		public static List<String[]> readeQQ(InputStream is) {
			try {

				List<String[]> result = new ArrayList<>();//最终返回的结果集
				List<String[]> tempArray = new ArrayList<>();//中间的结果集
				String[] temp = new String[4];
					
				    InputStreamReader isr= new InputStreamReader(is, "utf-8");
					BufferedReader bufferedReader = new BufferedReader(isr);
					String line = null;
					
					int count = 0;
					boolean flag = false;
					while ((line = bufferedReader.readLine()) != null) {
						if ("1".equals(trimStr(line))) {//1标示是第一个群成员， 开始解析群成员
							flag = true;
						}
						if (flag) {
							if (line.split("	").length > 4) {//表示是一个群成员信息的最后一行内容
								temp[count] = line;
								count = 0;
								
								tempArray.add(temp);
								temp = null;
								temp = new String[4];
							} else {
								temp[count] = line;
								count++;
							}
						} 
						
					}
					isr.close();
				
				
				//整合返回结果集
				for (String[] strArry : tempArray) {
					
					if(temp != null && temp.length > 0){
						temp = null;
						temp = new String[4];
					}
					
					temp[0] = trimStr(strArry[1]);
					if(strArry[3] != null){
						temp[1] = trimStr(strArry[3].split("	")[0]);
					} else {
						temp[1] = trimStr(strArry[2].split("	")[0]);
					}
					result.add(temp);
				}
				
				return result;
				
			} catch (Exception e) {
				System.out.println("读取文件内容出错");
				e.printStackTrace();
				return null;
			}

		}
		
		private static List<String> justify(String[] info, int colCount) {
			List<String> member = new ArrayList<String>();
			CollectionUtils.addAll(member, info);
			if (info.length == colCount) {
				member.add(2, "");
			} else if (info.length > colCount + 1) {
				String name = "";
				for (int i = info.length - colCount; i >= 1; i--) {
					name = member.get(i) + name;
					member.remove(i);
				}
				member.add(1, name);
			}
			return member;
		}
	}
	
	

	
	
	/**
	 * 
	 * @Desc : 去除字符串多空格
	 * @Author: RICK
	 * @Date : 2017年3月17日上午12:43:19
	 * @params:@param str
	 * @params:@return
	 *
	 */
	public static String trimStr(String str){
		return str.replaceAll("\\s*", "");
		
	}
}
